<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 我的订单</title>
    <link rel="stylesheet" href="styles.css">
    <script src="scripts.js"></script>
    <style>
        /* 重置盒模型 */
        *, *::before, *::after {
            box-sizing: border-box;
        }
        
        .header {
            width: 100%;
            background-color: #fff;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
        }
        .header img {
            height: 40px;
        }
        .orders-list {
            
            padding: 20px;
            width: 100%;
            padding-bottom: 60px; 
        }
        
        .order-item {
            margin-bottom: 20px; /* 增加订单之间的间距 */
            padding: 15px;
            background-color: #f9f9f9; /* 浅灰色背景 */
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .order-item h2 {
            margin-bottom: 10px; /* 标题和内容之间的间距 */
        }

        .order-item div {
            width: 100%;
        }

        .order-item p {
            flex: 1;
            text-align: center; /* 居中显示每个内容 */
            margin: 0; /* 移除默认外边距 */
        }

        .order-item div:not(:last-child) {
            margin-bottom: 10px; /* 每个区块之间的间距 */
        }

        .order-item button {
            flex: 1;
            max-width: 100px; 
            text-align: center;
        }

        .feedback-button {
            background-color: #7637c8; 
            border: none;
            color: white; 
            padding: 8px 12px; 
            border-radius: 4px; 
            cursor: pointer; 
            font-size: 14px;
            margin-left: 10px; 
        }

        .feedback-button:hover {
            background-color: #ff00aa; 
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2); 
        }

        .feedback-button:active {
            background-color: #1e7e34; 
            transform: scale(0.98); 
        }


        .footer-buttons {
            width: 100%; 
            background-color: #ffffff;
            color: #fff; 
            position: fixed; 
            bottom: 0; 
            left: 0; 
            z-index: 1000; 
            padding: 10px 0; 
            display: flex; 
            justify-content: space-between;
            box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
            padding-left: 10px; 
            padding-right: 10px; 
        }

        .footer-buttons button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        .footer-buttons button:hover {
            background-color: #0056b3;
        }
        /* 弹窗样式 */
        .modal {
            display: none; 
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .close-btn {
            background-color: transparent;
            border: none;
            font-size: 20px;
            cursor: pointer;
        }
        .stars {
            display: flex;
            margin: 10px 0;
        }
        .star {
            width: 30px;
            height: 30px;
            background-color: #ccc;
            clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
            margin-right: 5px;
            cursor: pointer;
        }
        .star.checked {
            background-color: gold;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <img src="./images/cafeteria-logo.png" alt="Logo">
            <div class="user">
                <span id="userPhone">你好，<span id="userPhoneNumber"></span></span>
                <button onclick="logoutUser()">退出</button>
            </div>
        </div>
        <h1 class="title">我的订单</h1>

        <!-- 订单列表 -->
        <div id="orders" class="orders-list">
            <!-- 订单项通过 JavaScript 动态渲染 -->
        </div>

        <!-- 弹窗 -->
        <div id="feedback-modal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>订单评价</h3>
                    <button class="close-btn" onclick="closeFeedbackModal()">×</button>
                </div>
                <div id="star-rating" class="stars">
                    <div class="star" data-rating="1"></div>
                    <div class="star" data-rating="2"></div>
                    <div class="star" data-rating="3"></div>
                    <div class="star" data-rating="4"></div>
                    <div class="star" data-rating="5"></div>
                </div>
                <textarea id="comment" rows="4" placeholder="输入评价..."></textarea>
                <button id="submit-feedback-btn" onclick="submitFeedback()">提交评价</button>
            </div>
        </div>
    </div>

    <div class="footer-buttons">
        <a href="consumer-dashboard.html"><button>菜单</button></a>
        <a href="cart.html"><button>购物车</button></a>
        <a href="rank.html"><button>排行榜</button></a>
        <a href="my.html"><button>我的</button></a>
        
    </div>

    <script>
        function loadUserInfo() {
            fetch('/api/user_info')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('userPhoneNumber').innerText = data.phone_number || '未知';
                    } else {
                        document.getElementById('userPhoneNumber').innerText = '未知';
                    }
                })
                .catch(error => {
                    console.error('Failed to fetch user info:', error);
                    document.getElementById('userPhoneNumber').innerText = '未知';
                });
        }
        // 在页面加载时调用此函数
        document.addEventListener('DOMContentLoaded', loadUserInfo);


        let currentOrderId, currentProductId;

        async function fetchOrders() {
            const response = await fetch('/api/orders');
            const orders = await response.json();

            const ordersContainer = document.getElementById('orders');
            ordersContainer.innerHTML = ''; // 清空现有订单

            if (!orders || orders.length === 0) {
                ordersContainer.innerHTML = "<p>没有找到订单。</p>";
                return;
            }

            orders.forEach(order => {
                const statusMapping = {
                    'pending': '制作中',
                    'completed': '已完成',
                    'cancelled': '已取消'
                };

                const orderElement = document.createElement('div');
                orderElement.classList.add('order-item');

                orderElement.innerHTML = `
                    <div>
                        <h2>订单号: ${order.id}</h2>
                        <!-- 总价, 状态, 创建时间均匀分布 -->
                        <div style="display: flex; justify-content: space-around; align-items: center; margin-top: 10px;">
                            <p>总价: ¥${order.total_price}</p>
                            <p>状态: ${statusMapping[order.status] || '未知'}</p>
                            <p>创建时间: ${new Date(order.created_at).toLocaleString()}</p>
                        </div>
                        <!-- 商品信息，每种商品的信息均匀分布 -->
                        ${order.items.map(item => `
                            <div style="display: flex; justify-content: space-around; align-items: center; margin-top: 10px; border-top: 1px solid #ccc; padding-top: 10px;">
                                <p>商品: ${item.product_name}</p>
                                <p>数量: ${item.quantity}</p>
                                <p>单价: ¥${item.price}</p>
                                <button class="feedback-button" onclick="openFeedbackModal(${order.id}, ${item.product_id})">评价</button>
                            </div>
                        `).join('')}
                    <!-- 催单按钮 -->
                    ${order.status !== 'completed' ? `
                        <button class="feedback-button" style="background-color: #f59e0b;" onclick="urgeOrder(${order.id})">催单</button>
                    ` : ''}
                        
                    </div>
                `;
                ordersContainer.appendChild(orderElement);
            });
        }

        function openFeedbackModal(orderId, productId) {
            currentOrderId = orderId;
            currentProductId = productId;
            document.getElementById('feedback-modal').style.display = 'flex';

            const stars = document.querySelectorAll('#star-rating .star');
            stars.forEach(star => {
                star.classList.remove('checked'); // 移除所有星星的 checked 类
                star.addEventListener('click', function() {
                    stars.forEach(s => s.classList.remove('checked')); // 移除所有星星的 checked 类
                    this.classList.add('checked'); // 只为当前点击的星星添加 checked 类
                    const rating = this.getAttribute('data-rating');
                    setStarRating(rating); // 更新星级评分
                });
            });
        }


        function closeFeedbackModal() {
            document.getElementById('feedback-modal').style.display = 'none';
            document.getElementById('comment').value = ''; // 清空评价内容
            const stars = document.querySelectorAll('#star-rating .star');
            stars.forEach(star => star.classList.remove('checked')); // 重置星级评分
        }


        function setStarRating(rating) {
            const stars = document.querySelectorAll('#star-rating .star');
            stars.forEach(star => {
                if (parseInt(star.getAttribute('data-rating')) <= rating) {
                    star.classList.add('checked');
                } else {
                    star.classList.remove('checked');
                }
            });
        }

        function submitFeedback() {
            const checkedStars = document.querySelectorAll('#star-rating .checked');
            let rating = null;
            if (checkedStars.length > 0) {
                rating = parseInt(checkedStars[checkedStars.length - 1].getAttribute('data-rating'));
            }
            const comment = document.getElementById('comment').value.trim();

            if (rating === null || comment === '') {
                alert('请填写所有评价字段。');
                return;
            }

            const orderId = currentOrderId; // 确保这个变量在 openFeedbackModal 函数中被正确设置
            const productId = currentProductId; // 确保这个变量在适当的地方被设置

            fetch('/api/feedback', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    order_id: orderId,
                    product_id: productId,
                    rating: rating,
                    comment: comment
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('评价已提交');
                    closeFeedbackModal(); 
                    fetchOrders(); 
                } else {
                    alert('提交评价失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('提交评价失败');
            });
        }

        window.onload = fetchOrders;


    async function logoutUser() {
        try {
            const response = await fetch('/api/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            const result = await response.json();
            if (result.success) {
                alert(result.message);
                // 跳转到登录页面
                window.location.href = 'login.html';
            } else {
                alert('登出失败，请重试！');
            }
        } catch (error) {
            console.error('登出时发生错误:', error);
            alert('无法连接到服务器，请稍后重试！');
        }
    }

    function urgeOrder(orderId) {
        fetch('/api/urge-order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ order_id: orderId })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                alert('催单成功！');
                // 可以在这里刷新订单列表或者执行其他操作
            } else {
                alert('催单失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('催单失败');
        });
    }




    </script>
</body>
</html>
